package com.bifang.module.file.core.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.module.file.common.vo.FileInfoVO;
import com.bifang.module.file.core.biz.FileInfoIntegration;
import com.bifang.module.file.dao.model.*;
import com.bifang.module.file.dao.service.*;
import com.bifang.module.system.core.dao.model.SysApplication;
import com.bifang.module.system.core.dao.service.SysApplicationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.module.file.common.vo.fileCollectData.FileCollectDataVO;
import com.bifang.module.file.common.vo.fileCollectData.FileCollectDataKeyVO;
import com.bifang.module.file.common.vo.fileCollectData.FileCollectDataQueryVO;
import com.bifang.module.file.core.biz.FileCollectDataIntegration;

/**
 * 文件信息表业务实现类
 *
 * @author xyh
 * @since 2023-03-22
 */
@ApiService(funcCode = "fileCollectData", title = "文件信息表")
public class FileCollectDataIntegrationImpl implements FileCollectDataIntegration {

    @Autowired
    public FileCollectDataService fileCollectDataService;
    @Autowired
    private FileInfoIntegration fileInfoIntegration;
    @Autowired
    FileMetadataService fileMetadataService;
    @Autowired
    FileFieldClassService fileFieldClassService;
    @Autowired
    FileClassService fileClassService;
    @Autowired
    SysApplicationService sysApplicationService;

    @Autowired
    public FileCollectService fileCollectService;

    @Override
    @OpApi(funcCode = "fileCollectData0001", title = "文件信息表分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<FileCollectDataVO> getList(FileCollectDataQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        List<String> fileClassCodeList=new ArrayList<>();
        List<BigDecimal> fileIdList=new ArrayList<>();
        if(!StringUtils.isEmpty(vo.getFieldId())){
            if(!StringUtils.isEmpty(vo.getFieldValue())){
                QueryWrapper<FileMetadata> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().eq(FileMetadata::getFileFieldId,vo.getFieldId())
                        .like(FileMetadata::getFieldValue,vo.getFieldValue());
                List<FileMetadata> list = fileMetadataService.list(queryWrapper);
                for(FileMetadata fileMetadata:list){
                    fileIdList.add(fileMetadata.getFileId());
                }
            }else{
                //根据元字段查询分类信息
                QueryWrapper<FileFieldClass> queryWrapper=new QueryWrapper<>();
                queryWrapper.lambda().select(FileFieldClass::getFileClassCode)
                        .eq(FileFieldClass::getFieldId,vo.getFieldId());
                List<FileFieldClass> list = fileFieldClassService.list(queryWrapper);
                for(FileFieldClass fileFieldClass:list){
                    fileClassCodeList.add(fileFieldClass.getFileClassCode());
                }
            }
        }
        QueryWrapper<FileCollectData> query = new QueryWrapper<>();
        query.lambda().eq(!ObjectUtils.isEmpty(vo.getUpAppId()), FileCollectData::getUpAppId, vo.getUpAppId())
                .eq(!ObjectUtils.isEmpty(vo.getSecrecyLevel()), FileCollectData::getSecrecyLevel, vo.getSecrecyLevel());

        if(!CollectionUtils.isEmpty(fileClassCodeList)){
            query.lambda().in(FileCollectData::getFileClassCode,fileClassCodeList);
        }
        if(!CollectionUtils.isEmpty(fileIdList)){
            query.lambda().in(FileCollectData::getFileId,fileIdList);
        }
        List<FileCollectData> list = fileCollectDataService.list();
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<FileCollectData> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<FileCollectDataVO> resultList = Convert.toList(FileCollectDataVO.class, pageInfo.getList());
        for(FileCollectDataVO item:resultList){
            String fileClassCode = item.getFileClassCode();
            FileClass fileClass = fileClassService.getById(fileClassCode);
            if(!ObjectUtils.isEmpty(fileClass)){
                item.setClassTitle(fileClass.getClassTitle());
            }
            String fileCollectCode = item.getFileCollectCode();
            if(fileCollectCode!=null&&!("").equals(fileCollectCode)){
                FileCollect fileCollect = fileCollectService.getById(fileCollectCode);
                item.setCollectTitle(fileCollect.getCollectTitle());
            }

        }
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "fileCollectData0002", title = "文件信息表根据主键查询详情", funcType = FuncTypeEnum.query)
    public FileCollectDataVO getById(FileCollectDataKeyVO vo) {
        FileCollectData entity = fileCollectDataService.getById(vo.getCollectDataId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        FileCollectDataVO result = Convert.convert(FileCollectDataVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "fileCollectData0003", title = "文件信息表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(FileCollectDataVO vo) {
        //主键为空为新增校验

        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "fileCollectData0004", title = "文件信息表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "fileCollectData0004",
            operationName = "文件信息表新增",
            dataType = "collectDataId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public FileCollectDataVO add(FileCollectDataVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        FileCollectData entity = Convert.convert(FileCollectData.class, vo);
        fileCollectDataService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setCollectDataId(entity.getCollectDataId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "fileCollectData0005", title = "文件信息表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "fileCollectData0005",
            operationName = "文件信息表修改",
            dataType = "collectDataId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public FileCollectDataVO edit(FileCollectDataVO vo) {
        if (ObjectUtils.isEmpty(vo.getCollectDataId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        FileCollectData oldEntity = fileCollectDataService.getById(vo.getCollectDataId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        FileCollectData entity = Convert.convert(FileCollectData.class, vo);
        fileCollectDataService.updateById(entity);
        return vo;
    }

    @Override
    @OpApi(funcCode = "fileCollectData0006", title = "文件信息表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "fileCollectData0006",
            operationName = "文件信息表删除",
            dataType = "collectDataId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(FileCollectDataKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getCollectDataId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        FileCollectData entity = fileCollectDataService.getById(vo.getCollectDataId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        fileCollectDataService.removeById(vo.getCollectDataId());
    }

    @Override
    @OpApi(funcCode = "fileCollectData0007", title = "文件信息归集", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "fileCollectData0007",
            operationName = "文件信息归集",
            dataType = "collectDataId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public FileCollectDataVO addCollect(FileCollectDataVO vo) {
        List<String> fileIds = vo.getFileIds();
        if(ObjectUtils.isEmpty(vo.getFileCollectCode())){
            throw new AppException("请选择文件分类树!");
        }
        int fSize = fileIds.size();
        if(fSize<=0){
            throw new AppException("请选择需要归集的数据!");
        }

        for(String fileId:fileIds){
            QueryWrapper<FileCollectData> fileCollectDataWrapper = new QueryWrapper<>();
            fileCollectDataWrapper.lambda().eq(!ObjectUtils.isEmpty(fileId), FileCollectData::getFileId, fileId)
                    .eq(!ObjectUtils.isEmpty(vo.getFileCollectCode()), FileCollectData::getFileCollectCode, vo.getFileCollectCode());
            List<FileCollectData> listHave = fileCollectDataService.list(fileCollectDataWrapper);
            if(listHave.size()>0&&fSize==1){
                throw new AppException("该文件信息已归集!");
            }
            if(listHave.size()<=0){
                BigDecimal fileIdParam = new BigDecimal(fileId);
                FileInfoVO fileInfoVO = fileInfoIntegration.getFileInfoDetail(fileIdParam);
                FileCollectData fileCollectData = new FileCollectData();
                BeanUtil.copyProperties(fileInfoVO,fileCollectData);
                fileCollectData.setFileCollectCode(vo.getFileCollectCode());
                //归档编码(生成规则为（时间202303241011+6位数字随机数+归档编码）)
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                String nowtime = sdf.format(new Date());
                //System.out.println("时间："+nowtime);

                String ranNum  = RandomUtil.randomNumbers(6);
                //System.out.println("aaaaaaaaaa:"+ranNum);

                String collectDataCode = nowtime+ranNum+vo.getFileCollectCode()+"";
                //System.out.println("collectDataCode：:"+collectDataCode);
                fileCollectData.setCollectDataCode(collectDataCode);

                fileCollectDataService.save(fileCollectData);
            }

        }
        return vo;
    }

}
